﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace ApplicationTemplate
{
    public partial class ApplcationTemplate : Form
    {
        public BaseDAM dam;

        public ApplcationTemplate()
        {
            InitializeComponent();
        }


        private void CmdExcute_Click(object sender, EventArgs e)
        {
            String tableName = this.CmbTableList.Text;

            if (String.IsNullOrEmpty(this.TxtNameSpace.Text.Trim()))
            {
                MessageBox.Show("请输入NameSpace。");
                return;
            }

            if (String.IsNullOrEmpty(tableName))
            {
                MessageBox.Show("请输入表名称。");
                return;
            }

            DataSet ds = SQLClass.GetTableFields(dam, tableName);

            this.TxtModel.Text = CreateModelClass.CreateModelTemplate(
                this.TxtNameSpace.Text,
                this.GetModelClassName(),
                CreateModelClass.CreateModelFields(ds));

            this.TxtDAM.Text = CreateDamClass.CreateDAMTemplate(
                this.TxtNameSpace.Text,
                this.GetDAMClassName(),
                this.GetDAMClassName(),
                this.GetModelClassName(),
                this.CmbTableList.Text.ToString(), ds);

            this.TxtDAC.Text = CreateDacClass.CreateDACTemplate(
                this.TxtNameSpace.Text,
                this.GetDACClassName(),
                this.GetDAMClassName(),
                this.GetDAMClassName(),
                this.GetModelClassName(),
                this.CmbTableList.Text.ToString(), ds);
        }

        public String GetTableName()
        {
            //Modify by wangsw 20121018
            return GetTableName(this.CmbTableList.Text);
        }

        public static String GetTableName(String tbName)
        {
            String[] info = tbName.Split('_');

            String clsName = "";
            foreach (String s in info)
            {
                if (s != "TB")
                {
                    clsName += s.Substring(0, 1).ToUpper() + s.Substring(1);
                }
            }

            return clsName;

            //tbName = tbName.Substring(tbName.IndexOf("_") + 1);
            //if (tbName.LastIndexOf("_") > 0)
            //{
            //    tbName = tbName.Substring(0, tbName.LastIndexOf("_"));
            //}
            //return tbName;
        }

        private String GetModelClassName()
        {
            return GetTableName() + "Model";
        }

        private String GetDAMClassName()
        {
            return GetTableName() + "DAM";
        }

        private String GetDACClassName()
        {
            return GetTableName() + "DAC";
        }

        private void CmdSave_Click(object sender, EventArgs e)
        {
            String ns = this.TxtNameSpace.Text;

            ns = ns.Replace("Watabe.", "").Replace(".", "\\");
            folderBrowserDialog1.SelectedPath = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("ApplicationTemplate")) + ns + "\\";
            DialogResult result = this.folderBrowserDialog1.ShowDialog();
            String path = folderBrowserDialog1.SelectedPath + "\\";

            if (result == DialogResult.OK)
            {
                if (MessageBox.Show("保存到" + path + "下，确定吗？", "文件保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    String appName = this.TxtNameSpace.Text.Substring(this.TxtNameSpace.Text.LastIndexOf(".") + 1);

                    String dacPath = path + appName + "\\Dac";
                    if (!Directory.Exists(dacPath))
                    {
                        Directory.CreateDirectory(dacPath);
                    }
                    StreamWriter sw = new StreamWriter(new FileStream(dacPath + "\\" + this.GetDACClassName() + ".cs", FileMode.Create), Encoding.UTF8);
                    sw.Write(TxtDAC.Text);
                    sw.Flush();
                    sw.Close();

                    AppendClass(path + appName + "\\" + appName + ".csproj", this.GetDACClassName() + ".cs");

                    String modelPath = path + appName + "\\Model";
                    if (!Directory.Exists(modelPath))
                    {
                        Directory.CreateDirectory(modelPath);
                    }
                    sw = new StreamWriter(new FileStream(modelPath + "\\" + this.GetModelClassName() + ".cs", FileMode.Create), Encoding.UTF8);
                    sw.Write(TxtModel.Text);
                    sw.Flush();
                    sw.Close();

                    AppendClass(path + appName + "\\" + appName + ".csproj", "Model\\" + this.GetModelClassName() + ".cs");

                    String DAMPath = path + appName + "\\Dam";
                    if (!Directory.Exists(DAMPath))
                    {
                        Directory.CreateDirectory(DAMPath);
                    }
                    sw = new StreamWriter(new FileStream(DAMPath + "\\" + this.GetDAMClassName() + ".cs", FileMode.Create), Encoding.UTF8);
                    sw.Write(TxtDAM.Text);
                    sw.Flush();
                    sw.Close();

                    AppendClass(path + appName + "\\" + appName + ".csproj", "Dam\\" + this.GetDAMClassName() + ".cs");


                    TxtFolder.Text = path + "中保存成功。";
                }
            }

        }

        private void CmdTest_Click(object sender, EventArgs e)
        {
            try
            {
                dam = new BaseDAM(this.ServerName.Text, this.DatabaseName.Text, this.LoginId.Text, this.Password.Text);
                DataSet ds = dam.TableList;
                this.CmbTableList.DataSource = ds.Tables[0];
                this.CmbTableList.DisplayMember = "name";
                this.CmbTableList.ValueMember = "name";


                LblMsg.Text = "数据库连接成功，可以生成代码。";
                LblMsg.Visible = true;
                this.CmbTableList.Enabled = true;
                this.CmdExcute.Enabled = true;
                this.TxtNameSpace.Enabled = true;
                this.CmdCreateProject.Enabled = true;
            }
            catch (Exception ex)
            {
                LblMsg.Visible = false;
                this.CmbTableList.Enabled = false;
                this.CmdExcute.Enabled = false;
                this.TxtNameSpace.Enabled = false;
                this.CmdCreateProject.Enabled = false;
                MessageBox.Show("数据库连接失败。" + ex.Message);
            }

        }

        private void CmdCreateProject_Click(object sender, EventArgs e)
        {


            String appPath = this.TxtNameSpace.Text.Replace("Watabe.", "").Replace(".", "\\");
            String appName = appPath.Substring(appPath.LastIndexOf("\\") + 1);
            String rootPath = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("ApplicationTemplate"));

            String appFullPath = rootPath + appPath + "\\";

            if (Directory.Exists(appFullPath))
            {
                return;
            }
            else
            {
                Directory.CreateDirectory(appFullPath);
                Directory.CreateDirectory(appFullPath + appName);
                Directory.CreateDirectory(appFullPath + appName + "\\Dam");
                Directory.CreateDirectory(appFullPath + appName + "\\Model");
                Directory.CreateDirectory(appFullPath + appName + "\\Properties");

            }
        }

        public void ReplaceInPath(string filePath, string searchText, string replaceText)
        {
            if (Directory.Exists(filePath))
            {
                foreach (string file in Directory.GetFiles(filePath))
                {
                    ReplaceInFile(file, searchText, replaceText);
                }
                foreach (string path in Directory.GetDirectories(filePath))
                {
                    ReplaceInPath(path, searchText, replaceText);
                }
            }
            else if (File.Exists(filePath))
            {
                ReplaceInFile(filePath, searchText, replaceText);
            }
        }

        public void ReplaceInFile(string filePath, string searchText, string replaceText)
        {
            try
            {
                if (filePath.IndexOf("AssemblyInfo.cs") > 0 || filePath.IndexOf(".csproj") > 0 || filePath.IndexOf(".sln") > 0)
                {
                    StreamReader reader = new StreamReader(filePath, Encoding.UTF8);
                    string content = reader.ReadToEnd();
                    reader.Close();
                    content = Regex.Replace(content, searchText, replaceText);
                    StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8);
                    writer.Write(content);
                    writer.Close();
                }
            }
            catch (System.Exception e)
            {
            }
        }

        public void AppendClass(string filePath, String csClass)
        {
            try
            {
                if (filePath.IndexOf(".csproj") > 0)
                {
                    StreamReader reader = new StreamReader(filePath, Encoding.UTF8);
                    string content = reader.ReadToEnd();
                    reader.Close();
                    if (content.IndexOf(csClass) > 0)
                    {
                        return;
                    }

                    int index = content.IndexOf(@"<Compile Include=""Properties\AssemblyInfo.cs"" />");
                    content = content.Substring(0, index) + @"<Compile Include=""" + csClass + @""" />" + "\n    " + content.Substring(index);

                    StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8);
                    writer.Write(content);
                    writer.Close();
                }
            }
            catch (System.Exception e)
            {
            }
        }

    }
}